﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Autofac.Integration.Mvc;
using MovieDB.Common;
using MovieDB.Models;

namespace MovieDB.Modelbinder
{
    [ModelBinderType(typeof (MovieModel))]
    public class MovieModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var movieModel = base.BindModel(controllerContext, bindingContext) as MovieModel;
            if (movieModel == null)
            {
                return null;
            }

            string[] audioTypes = bindingContext.ValueProvider.GetValue("audioQuality.AudioType").AttemptedValue.Split(',');
            string[] audioChannels = bindingContext.ValueProvider.GetValue("audioQuality.AudioChannels").AttemptedValue.Split(',');

            movieModel.AudioQualities = CreateAudioQualityList(audioTypes, audioChannels);

            return movieModel;
        }

        private IList<AudioQualityModel> CreateAudioQualityList(string[] audioTypes, string[] audioChannels)
        {
            if (audioTypes == null)
            {
                throw new ArgumentNullException("audioTypes");
            }
            if (audioChannels == null)
            {
                throw new ArgumentNullException("audioChannels");
            }
            if (!HaveAllAudioTypesTheSameLength(audioTypes, audioChannels))
            {
                throw new ArgumentException("Alle AudioTypes must have the same length.");
            }


            return audioTypes.Select((value, index) => new AudioQualityModel
                                                           {
                                                               AudioType = audioTypes[index].ParseAsEnum<AudioType>(),
                                                               AudioChannels = audioChannels[index].ParseAsEnum<AudioChannels>()
                                                           }).ToList();
        }

        private bool HaveAllAudioTypesTheSameLength(string[] audioTypes, string[] audioChannels)
        {
            return audioTypes.Length == audioChannels.Length;
        }
    }
}